﻿Type=Service
Version=6
ModulesStructureVersion=1
B4A=true
@EndOfDesignText@
#Region  Service Attributes 
	#StartAtBoot: False
	#ExcludeFromLibrary: True
#End Region

Sub Process_Globals
	'These global variables will be declared once when the application starts.
	'These variables can be accessed from all modules.
	Public bIMConnected As Boolean=False
	Private aLoc As AMapLocationClient
	Private aloc_option As locationOption
	Public LocCity As AMapLocation
	'初始化数据的flg
	Public ui As myInfo
	Public nNetReq As Int
	Public nUnrateOrd As Int=0
	Private bugly As bugly
	Public getui As b4agetui
	Public RYIM As RongYunIMKit
	Private pe As PhoneEvents
	Private checkUpdateReq As checkupdatereq
End Sub

Sub Service_Create
	'This is the program entry point.
	If File.Exists("",comm.S_DATADIR)=False Then File.MakeDir("",comm.S_DATADIR)
	initloc '后台定位一次
	Dim pid As PhoneId
	pe.InitializeWithPhoneState("pe",pid)
	bugly.startCatching(comm.BUGLY_APPID)	
	getui.Init("gtpush")
	getui.OnStart
	'This is a good place to load resources that are not specific to a single activity.
	g_store.conf.Initialize(File.DirInternal,"kvstore.dat")
	comm.myUIL.init("uil")
	comm.myUIL.defScaleType=comm.myUIL.FIT_XY
	comm.L("PushStatus:"&getui.isPushTurnedOn)
	
	RYIM.init("ryim")
	If comm.isLogin Then
		comm.mi=g_store.get("myinfo")
		getui.bindAlias(comm.mi.usertel)'绑定推送别名
		comm.L("pushAlias:"&comm.mi.usertel)
		comm.L("pushcid:"&getui.Clientid)
		If comm.mi.rongyun_token.Length>4 Then
			RYIM.Connect(comm.mi.rongyun_token)
			comm.L("正在连接:"&comm.mi.rongyun_token)
		Else
			comm.L("IMToken长度无效")
		End If
	End If
	nNetReq=3
	If g_store.getDef("islogin",False) Then
		nNetReq=nNetReq+1
	End If
	Dim cs As String=g_store.getDef("cityjs","")
	If cs.Length<1 Then
		nNetReq=nNetReq+1
	End If
	
	initdata '初始化网络数据
	
	inittestdata
End Sub
'没有网络连接了自动停止定位
Sub pe_ConnectivityChanged (NetworkType As String, State As String, Intent As Intent)
	If State.EqualsIgnoreCase("connected") Then
		aLoc.StartLocation
	Else
		aLoc.StopLocation
		
	End If
	
End Sub
Sub conRY(tok As String)
	comm.L("正在连接")
	RYIM.Connect(tok)
End Sub
Sub reqCheckUpdate(tmp As checkupdatereq)
	checkUpdateReq=tmp
	ParseHelper.doGetReq(Me,"checkupdate",comm.getApi(comm.apiIdx.CHECKUPDATE),Null)
End Sub
Private Sub reqModifySubmit
	Dim jsg As JSONGenerator
	Dim m,m2 As Map
	m.Initialize
	m2.Initialize
	m2.Put("address",comm.mi.address)
	m2.Put("city",comm.mi.city)
	m2.Put("autograph",comm.mi.commit)
	m2.Put("sex",comm.mi.sex)
	m2.Put("nianji",comm.mi.grade)
	m2.Put("image",comm.mi.headimg)
	m2.Put("username",comm.mi.nickname)
	m2.Put("hy_school",comm.mi.school)
	m2.Put("age",comm.mi.age)
	'm2.Put("rongyun_token",comm.mi.rongyun_token)
	m.Put("data",m2)
	jsg.Initialize(m)
	Dim ar() As String=Array As String("data",jsg.ToString)
	ParseHelper.doPostReqArr(Me,"submit",comm.getApi(comm.apiIdx.MODIFYMYINFO),ar,"")
End Sub
Sub ryim_onError(code As Int,msg As String)
	bIMConnected=False
	comm.L("IM连接失败code:"&code&" msg:"&msg)
End Sub
Sub ryim_onSuccess(arg As String)
	bIMConnected=True
	comm.L("IM连接成功:"&arg)
	
End Sub
Sub ryim_onTokenIncorrect
	bIMConnected=False
	comm.L("IM连接失败,Token无效")
End Sub
Sub ryim_reqUserInfo(userId As String) As UserInfo_ry
	comm.L("reqUI:"&userId)
	Dim ui1 As UserInfo_ry=comm.getUserInfoForIM(userId)
	comm.L("reqUI:"&userId&" "&ui1.Name)
	Return ui1
End Sub
Sub ryim_onIMReceived(msg As String,nLeft As Int)
	comm.L("ryim_onIMReceived:"&msg)
	Dim noti As Notification
	noti.Initialize
	noti.Icon="icon"
	noti.AutoCancel=True
	noti.Light=True
	noti.Number=nLeft
	noti.SetInfo(Application.LabelName,msg,actmain)
	noti.Sound=True
	noti.Notify(0)
End Sub
'Sub jmsg_onjmsg(msg As Message_im)
'	Try
'		If msg.ContentTypeString.EqualsIgnoreCase("text") Then 	Log(msg.Contentjson)
'		Log(msg.FromID)
'		Log(msg.FromName)
''	Log(msg.TargetID)
''	Log(msg.FromID&" "&msg.Message)
'	Catch
'		Log(LastException.Message)
'	End Try
'	Log("end")
'End Sub
''Sub jmsg_onjmsgrecv(act As String,iw As Intent,ext As Bundle)
''	Try
''		Log("typ:"&ext.getString(jmsg.EXTRA_CONTENT_TYPE,"")&" msg:"&ext.getString(jmsg.EXTRA_MESSAGE,"")&" title:"&ext.getString(jmsg.EXTRA_TITLE,""))
''	Catch
''		Log(LastException)
''	End Try
''	
''	Log("act:"&act&iw.ExtrasToString)
''End Sub
'Sub jmsg_gotResult(eventtype As String,responseCode As Int,responseMessage As String,JsonStr As String)
'	comm.L("jmsg:"&responseCode&" "&responseMessage&" "&JsonStr)
'	Select eventtype.ToLowerCase
'	Case "register"
'		If responseCode=0 Or responseMessage.ToLowerCase.IndexOf("exist")>-1 Then
'			jmsg.login(comm.mi.usertel,comm.mi.jpush_pwd)
'			reqModifySubmit
'		Else
'			comm.L("注册失败:"&responseCode&" "&responseMessage)
'		End If
'	Case "login"
'		If responseCode=0 Then
'			comm.TL("Jmsg登录成功")
'			actmain.convList=jmsg.ConversationList
'			CallSubDelayed(actmain,"refushMsgList")
'		Else
'			comm.L("Jmsg登录失败:"&responseCode&" "&responseMessage)
'		End If
'	End Select
'End Sub
Sub gtpush_onRec(str As String,messageid As String,taskid As String)
	Log("gotPush:"&str)
End Sub
Sub gtpush_onClickid(str As String)
	Log("pushclicked:"&str)
End Sub
Sub Service_Start (StartingIntent As Intent)
	
	'doLogin("123456789","fdsafasd")
	If g_store.conf.GetDefault("islogin",False) Then
		ui=g_store.conf.Get("myinfo")
	End If
End Sub
#Region init
Sub initdata
	ParseHelper.doGetReq(Me,"banner",comm.getApi(comm.apiIdx.APPBANNER),Array As String("is_teach","0"))
	ParseHelper.doGetReq(Me,"kemu",comm.getApi(comm.apiIdx.KEMU),Null)
	ParseHelper.doGetReq(Me,"mstj",comm.getApi(comm.apiIdx.MSTJ),Null)
	If g_store.getDef("islogin",False) Then
		ParseHelper.doGetReq(Me,"unrate",comm.getApi(comm.apiIdx.REQUNRATENUM),Null)
	End If
	ParseHelper.doGetReq(Me,"getcitys",comm.getApi(comm.apiIdx.REQCITYLIST),Null)
	ParseHelper.doGetReq(Me,"getstartbg",comm.getApi(comm.apiIdx.APPSTARTBG),Null)
	ParseHelper.doGetReq(Me,"getad",comm.getApi(comm.apiIdx.GETADIMG),Null)
	ParseHelper.doGetReq(Me,"xtgg",comm.getApi(comm.apiIdx.GETXTGG),Null)
End Sub
Sub inittestdata
'	Dim arr() As String=Array As String("语文","数学","英语","物理","化学","地理","历史","奥数","生物","政治")
	Dim lst As List
'	lst.Initialize
'	For i=0 To arr.Length-1
'		Dim st As Subject
'		st.Initialize
'		st.name=arr(i)
'		st.img="http://assets.alicdn.com/apps/mytaobao/3.0/profile/defaultAvatar/avatar-60.png"
'		lst.Add(st)
'	Next
'	Dim lst As List
'	lst.Initialize
'	g_store.conf.Put(comm.S_SUBJECTS,lst)
	lst.Initialize
	lst.AddAll(Array As String("智能排序","学生最多","评论最多","评论最低","金额最高","金额最低"))
	g_store.conf.Put(comm.S_PAIXU_FINDTEACHER,lst)
	lst.Initialize()
	lst.AddAll(Array As String("一年级","二年级","三年级","四年级","五年级","六年级","初一","初二","初三","高一","高二","高三"))
	g_store.conf.Put(comm.S_NIANJI_FINDTEACHER,lst)
	lst.Initialize
	lst.AddAll(Array As String("乌鲁木齐市","克拉玛依市","吐鲁番市","哈密市","昌吉市","阜康市","米泉市","博乐市","库尔勒市","阿克苏市","阿图什市","喀什市","和田市","奎屯市","伊宁市","塔城市","乌苏市","阿勒泰市"))
	g_store.conf.Put(comm.S_CITYLIST,lst)
	lst.Initialize
	lst.AddAll(Array As String("学生上门","老师上门","协商地址"))
	g_store.conf.Put(comm.S_SKFS,lst)
End Sub
'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
	'这里不能用msgbox
	Log("UnhandleErr:"&Error&CRLF&StackTrace)
	comm.T("不好意思，程序出错咯")
	Return False
End Sub
#End Region
#Region 网络请求


Sub JobDone(thj As HttpJob)
	If thj.Success Then
		Dim str As String=thj.GetString
		If thj.JobName.EqualsIgnoreCase("downloadappbg")=False Then Log("Job:"&thj.JobName&" js:"&str)
		Dim nr As netRes=ParseHelper.getStatusData(str)
		Select thj.JobName
		Case "xtgg"
			If nr.nCode=200 Then
				Dim parser As JSONParser 
				parser.Initialize(str) 
				Dim root As Map = parser.NextObject 
				Dim data As List = root.Get("data") 
				g_store.put("xtgg",data)				
			End If
			
			

		Case "getad"
			Dim parser As JSONParser 
			parser.Initialize(str) 
			Dim root As Map = parser.NextObject 
			Dim dataad As String = root.GetDefault("data","") 
			Dim status As String = root.GetDefault("status","") 
			If dataad.Length>0 Then g_store.put("adimg",comm.combinPic(dataad))
		Case "downloadappbg"
			Try
				Dim ops As OutputStream= File.OpenOutput(File.DirInternal,"bg.png",False)
				File.Copy2(thj.GetInputStream,ops)
				ops.Flush
				ops.Close
				comm.L("appbg download ok")
				
			Catch
				comm.L("保存appbg错误:"&LastException.Message)
				g_store.put("lastbg","")'清理标志
			End Try
		Case "getstartbg"
			If nr.nCode=200 Then
				Dim parser As JSONParser 
				parser.Initialize(str) 
				Dim root1 As Map = parser.NextObject 
				Dim data1 As String = root1.GetDefault("data","") 
				If data1.Length>5 Then
					Dim lastbg As String=g_store.getDef("lastbg","")
					'如果图片的url和上次不同再下载一次
'					comm.L("lastbg:"&lastbg)
'					comm.L("newbg:"&data1)
					If lastbg.EqualsIgnoreCase(data1)=False Or File.Exists(File.DirInternal,"bg.png")=False Then
						comm.L("download newbg")
						g_store.put("lastbg",data1)
						ParseHelper.doGetReq(Me,"downloadappbg",data1,Null)
					End If
				End If	
				
			End If
		Case "banner"
			If nr.nCode=200 Then
				g_store.conf.Put("banner",ParseHelper.parseBanner(str))
				nNetReq=nNetReq-1
			End If
		Case "kemu"
			If nr.nCode=200 Then
				g_store.conf.Put(comm.S_SUBJECTS,ParseHelper.parseKemu(str))
				nNetReq=nNetReq-1
			End If
		Case "mstj"
			If nr.nCode=200 Then
				Dim jsLst As List=ParseHelper.parseTeacher(str)
				g_store.conf.Put("mstjlst",jsLst)
				nNetReq=nNetReq-1
			Else
				Log("获取名师推荐出错:"&nr.sData)
				CallSubDelayed2(Main,"onErr",nr.sData)
			End If
		Case "unrate"
			If nr.nCode=200 Then
				Dim parser As JSONParser 
				parser.Initialize(str) 
				Dim root As Map = parser.NextObject 
				Dim data As List = root.Get("data") 
				For Each coldata As Map In data 
				    Dim c As String = coldata.Get("c") 
					nUnrateOrd=c
				Next 
				nNetReq=nNetReq-1
			Else
				comm.L("获取未评价订单数量错误:"&nr.sData)
				g_store.put("islogin",False)
			End If
		Case "getcitys"
			Dim cs As String=g_store.getDef("cityjs","")
			If cs.Length<1 Then nNetReq=nNetReq-1
			g_store.put("cityjs",str)
		Case "checkupdate"
			Dim parser As JSONParser 
			parser.Initialize(str) 
			Dim root As Map = parser.NextObject 
			Dim content As String = root.GetDefault("data","") 
			Dim version As String = root.GetDefault("version","") 
			Dim url As String = root.GetDefault("url","") 
			Dim tCur As checkupdateres
			tCur.Initialize
			tCur.url=url&"?t="&DateTime.Now
			tCur.ver=version.ToLowerCase.Replace("v","").Replace("ver","")
			tCur.content=content
			tCur.status=nr.nCode
			CallSubDelayed2(checkUpdateReq.cb,"checkupdateover",tCur)
		End Select
	Else
		comm.TL("name:"&thj.JobName&" Err:"&thj.ErrorMessage)
		If nNetReq>0 Then
			'初始化未完成
			CallSubDelayed2(Main,"onErr","jobname:"&thj.JobName&" "&thj.ErrorMessage)
			StopService(Me)
		End If
	End If
'	If nNetReq=0 Then
'		'网络数据初始化完毕
'
'	End If
	thj.Release
End Sub


#End Region
#Region 定位
Sub Service_Destroy
	Try
		g_store.conf.Close	
		aLoc.OnDestory
		RYIM.logout
		RYIM.disconnect
		getui.OnStop
		getui.OnStopService
		Log("destory RYIM")
	Catch
		Log(LastException.Message)
	End Try
	
End Sub
Sub initloc
	aLoc.Init("aloc")
	aloc_option.init
	aloc_option.Interval=3000
	aloc_option.GPSFirst=False
	aloc_option.MockEnable=True
	aloc_option.LocationMode=aloc_option.Battery_Saving
	aloc_option.OnceLocation=True
	aLoc.LocationOption=aloc_option
	aLoc.StartLocation
End Sub
Sub aloc_onLocationChanged(loc As AMapLocation)
'	Dim str As String="addr:"&loc.Address&" City:"&loc.City&" Road:"&loc.Road&" Country:"&loc.Country&" District:"&loc.District&" Latitude:"&loc.Latitude&" Longitude:"&loc.Longitude&" LocationDetail:"&loc.LocationDetail _
'	&" PoiName:"&loc.PoiName&" Province:"&loc.Province&" Street:"&loc.Street&CRLF&CRLF&"Str:"&loc.toStr
'	Log(loc.toStr)
'	'out puts:
'	'{"country":"中国","province":"新疆维吾尔自治区","city":"乌鲁木齐市","cityCode":"0991","district":"新市区","adCode":"650104","address":"新疆维吾尔自治区乌鲁木齐市新市区鲤鱼山路靠近领世广场","road":"鲤鱼山路","street":"鲤鱼山路","number":"298号","poiName":"领世广场","errorCode":0,"errorInfo":"success","locationDetail":"-5","altitude":0,"bearing":0,"speed":0,"satellites":0,"aoiName":"","desc":"新疆维吾尔自治区 乌鲁木齐市 新市区 鲤鱼山路 靠近领世广场","time":1458556366701,"locationType":2,"accuracy":91,"latitude":43.884021,"longitude":87.598392,"provider":"lbs"}
'	edtresult.Text="位置:"&str&CRLF&edtresult.Text
	'存起来下次使用
	g_store.put("lastlat",loc.Latitude)
	g_store.put("lastlng",loc.Longitude)
	LocCity=loc
	aLoc.StopLocation

End Sub

#End Region 